<?php
/**
 * Created by PhpStorm.
 * User: iyahe@qq.com (天明)
 * Date: 2017/12/3/003
 * Time: 12:24
 */
namespace app\common\controller;
use think\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;

class Upload extends Controller{
    private static $_instance;
    public static $auth;
    public static $token;
    public static $bucket;
    public static $host = 'http://img.he29.com/';
    public static function run($bucket='imgku') {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        self::init($bucket);
        self::$bucket = $bucket;
        return self::$_instance;
    }
    public static function init($bucket){
        $accessKey = '3ENXma-bs7xBsVWLK29NuqugX3mUcsXxaoaCRypX';
        $secretKey = '82vVHgZgUmOEhR8MaL0gkw_NdR5sf15e08vFmMYh';
        self::$auth = new Auth($accessKey, $secretKey);
        self::$token = self::$auth->uploadToken($bucket);
    }
    /** 图片上传到七牛云
     * @param        $filePath
     * @param string $name
     * @param string $ranme
     * @return array|bool
     */
    public function upload($filePath,$name='api',$ranme=''){
        $ext = getExtension($filePath);
        $key = $name . '/' . sha1(time()) .$ext;//上传到7牛需要保存的文件名
        if($ranme) $key = $ranme;
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile(self::$token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            $sucData = [
                'hash'=>$ret['hash'],
                'key'=>$ret['key'],
                'url'=>self::host() . $ret['key']
            ];
            $this->uploadSuccess($sucData,$name);
            return $sucData;
        }
    }
    public static function host(){
        return config('img_host');
    }
    public function uploadSuccess($sucData,$name){
        $this->writDB($sucData,$name);
    }
    public function writDB($data,$name){
        return Db::name('file_list')->insertGetId([
            'file_addtime'=>getStrtime(),
            'file_update_time'=>getStrtime(),
            'file_key'=>$data['key'],
            'file_hash'=>$data['hash'],
            'file_come'=>$name,
            'file_uid'=>'',
            'file_blar'=>self::$bucket,
            'file_type'=>'',
            'file_size'=>'',
            'file_ext'=>'',
            'file_host'=>self::$host
        ]);
    }
}